package com.co.oauth.controller;

import com.co.common.entity.Result;
import com.co.oauth.service.AuthService;
import com.co.oauth.util.AuthToken;
import com.co.user.pojo.ResultUser;
import com.co.user.pojo.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @PostMapping("/signup")
    public Result signup(@RequestBody User user) {
        String username = user.getUsername();
        String email = user.getEmail();
        String password = user.getPassword();
        //校验参数
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("请输入用户名");
        }

        if (StringUtils.isEmpty(email)) {
            throw new RuntimeException("请输入邮箱");
        }

        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("请输入密码");
        }
        authService.signup(username, email, password);
        return Result.ok("恭喜您，注册成功");
    }

    @PostMapping("/login")
    public Result<ResultUser> login(@RequestBody User user, HttpServletResponse response) {
        String username = user.getUsername();
        String password = user.getPassword();
        //校验参数
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("请输入用户名");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("请输入密码");
        }
        //申请令牌
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //将令牌短标识jti存入cookie
        Cookie cookie = new Cookie("uid", authToken.getJti());
        cookie.setDomain(cookieDomain);
        cookie.setPath("/");
        cookie.setMaxAge(cookieMaxAge);
        cookie.setHttpOnly(false);
        response.addCookie(cookie);

        User userInfo = authService.findUserByUsername(username);
        ResultUser resultUser = new ResultUser();
        resultUser.setJti(authToken.getJti());
        resultUser.setUserInfo(userInfo);
        return Result.ok(resultUser);
    }

}
